package modbus

import (
	"dgo/goutils/utils"
	"encoding/binary"
)

func BuildModbusBuf(id byte, func_id byte, data []byte) []byte {
	bb := utils.NewBytesBuilder()
	bb.Reset()
	bb.WriteByte(id)
	bb.WriteByte(func_id)
	bb.Write(data)
	bb.WriteUInt16_LE(CRC16(bb.Bytes()))
	return bb.Bytes()
}

func ExtractModbusBuf(buf []byte) (ok bool, addrid byte, funcid byte, data []byte) {
	if len(buf) < 4 {
		ok = false
		return
	}
	l := len(buf)
	crc0 := binary.LittleEndian.Uint16(buf[l-2:])
	crc1 := CRC16(buf[:l-2])
	ok = crc0 == crc1
	addrid = buf[0]
	funcid = buf[1]
	data = buf[2 : l-2]
	return
}
